import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hiot_cloud_app_v1/app/data/models/device_model.dart';
import 'package:hiot_cloud_app_v1/app/modules/device/controllers/add_device_controller.dart';
import 'package:hiot_cloud_app_v1/app/theme/app_colors.dart';
import 'package:hiot_cloud_app_v1/app/theme/app_text_styles.dart';

class AddDeviceView extends GetView<AddDeviceController> {
  const AddDeviceView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('添加设备'),
        centerTitle: true,
      ),
      body: Obx(() => _buildStepContent()),
      bottomNavigationBar: Obx(() => _buildBottomBar()),
    );
  }

  Widget _buildStepContent() {
    switch (controller.currentStep.value) {
      case 0:
        return _buildDeviceDiscoveryStep();
      case 1:
        return _buildDeviceInfoStep();
      case 2:
        return _buildDeviceConfigStep();
      default:
        return const SizedBox.shrink();
    }
  }

  Widget _buildDeviceDiscoveryStep() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '设备发现',
            style: AppTextStyles.titleLarge,
          ),
          const SizedBox(height: 16),
          Text(
            '请确保您的设备已开启并处于配网模式',
            style: AppTextStyles.bodyMedium,
          ),
          const SizedBox(height: 24),
          Obx(() => controller.isScanning.value
              ? _buildScanningView()
              : _buildScanControlView()),
          const SizedBox(height: 16),
          Expanded(
            child: Obx(() => controller.discoveredDevices.isEmpty
                ? _buildEmptyDevicesList()
                : _buildDevicesList()),
          ),
          const SizedBox(height: 16),
          _buildManualInputOption(),
        ],
      ),
    );
  }

  Widget _buildScanningView() {
    return Column(
      children: [
        const Center(
          child: SizedBox(
            width: 120,
            height: 120,
            child: CircularProgressIndicator(),
          ),
        ),
        const SizedBox(height: 16),
        Center(
          child: Text(
            '正在扫描设备...',
            style: AppTextStyles.titleMedium,
          ),
        ),
        const SizedBox(height: 24),
        ElevatedButton(
          onPressed: controller.stopScan,
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.grey,
            minimumSize: const Size(double.infinity, 50),
          ),
          child: const Text('停止扫描'),
        ),
      ],
    );
  }

  Widget _buildScanControlView() {
    return ElevatedButton(
      onPressed: controller.scanDevices,
      style: ElevatedButton.styleFrom(
        backgroundColor: AppColors.primary,
        minimumSize: const Size(double.infinity, 50),
      ),
      child: const Text('扫描设备'),
    );
  }

  Widget _buildEmptyDevicesList() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.devices_other,
            size: 64,
            color: Colors.grey,
          ),
          const SizedBox(height: 16),
          Text(
            '未发现设备',
            style: AppTextStyles.titleMedium.copyWith(color: Colors.grey),
          ),
          const SizedBox(height: 8),
          Text(
            '请确保设备已开启并处于配网模式',
            style: AppTextStyles.bodyMedium.copyWith(color: Colors.grey),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildDevicesList() {
    return ListView.separated(
      itemCount: controller.discoveredDevices.length,
      separatorBuilder: (context, index) => const Divider(),
      itemBuilder: (context, index) {
        final device = controller.discoveredDevices[index];
        return ListTile(
          leading: _getDeviceIcon(device.type),
          title: Text(device.name),
          subtitle: Text('ID: ${device.id}'),
          trailing: const Icon(Icons.chevron_right),
          onTap: () => controller.selectDevice(device),
        );
      },
    );
  }

  Widget _buildManualInputOption() {
    return TextButton(
      onPressed: () {
        Get.dialog(
          AlertDialog(
            title: const Text('手动添加设备'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                TextField(
                  decoration: const InputDecoration(
                    labelText: '设备ID',
                    hintText: '请输入设备ID',
                  ),
                  onChanged: (value) => controller.deviceId.value = value,
                ),
                TextField(
                  decoration: const InputDecoration(
                    labelText: '设备名称',
                    hintText: '请输入设备名称',
                  ),
                  onChanged: (value) => controller.deviceName.value = value,
                ),
                TextField(
                  decoration: const InputDecoration(
                    labelText: '设备类型',
                    hintText: '例如: LIGHT, SOCKET',
                  ),
                  onChanged: (value) => controller.deviceType.value = value,
                ),
                TextField(
                  decoration: const InputDecoration(
                    labelText: '设备IP地址',
                    hintText: '例如: 192.168.1.10',
                  ),
                  onChanged: (value) => controller.deviceIp.value = value,
                ),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Get.back(),
                child: const Text('取消'),
              ),
              TextButton(
                onPressed: () {
                  Get.back();
                  controller.nextStep();
                },
                child: const Text('确定'),
              ),
            ],
          ),
        );
      },
      child: const Text('手动输入设备信息'),
    );
  }

  Widget _buildDeviceInfoStep() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '设备信息',
            style: AppTextStyles.titleLarge,
          ),
          const SizedBox(height: 24),
          Card(
            elevation: 2,
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                children: [
                  _buildDeviceInfoItem(
                    '设备ID',
                    controller.deviceId.value,
                    Icons.vpn_key,
                  ),
                  const Divider(),
                  _buildDeviceInfoItem(
                    '设备名称',
                    controller.deviceName.value,
                    Icons.device_hub,
                  ),
                  const Divider(),
                  _buildDeviceInfoItem(
                    '设备类型',
                    controller.deviceType.value,
                    Icons.category,
                  ),
                  const Divider(),
                  _buildDeviceInfoItem(
                    '设备IP',
                    controller.deviceIp.value,
                    Icons.wifi,
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 24),
          Text(
            '设备名称',
            style: AppTextStyles.titleMedium,
          ),
          const SizedBox(height: 8),
          TextField(
            decoration: const InputDecoration(
              hintText: '请输入设备名称',
              border: OutlineInputBorder(),
            ),
            controller: TextEditingController(text: controller.deviceName.value),
            onChanged: controller.updateDeviceName,
          ),
          const SizedBox(height: 24),
          Text(
            '设备分组',
            style: AppTextStyles.titleMedium,
          ),
          const SizedBox(height: 8),
          _buildGroupDropdown(),
          const SizedBox(height: 16),
          TextButton(
            onPressed: () {
              Get.dialog(
                AlertDialog(
                  title: const Text('新建分组'),
                  content: TextField(
                    decoration: const InputDecoration(
                      labelText: '分组名称',
                      hintText: '请输入分组名称',
                    ),
                    controller: TextEditingController(),
                    onSubmitted: (value) {
                      controller.addDeviceGroup(value);
                      Get.back();
                    },
                  ),
                  actions: [
                    TextButton(
                      onPressed: () => Get.back(),
                      child: const Text('取消'),
                    ),
                    TextButton(
                      onPressed: () {
                        final String newGroup = 
                            (Get.overlayContext!.findRenderObject() as RenderBox)
                                .findDescendantRenderObjectOfType<RenderEditable>()!
                                .text!.toPlainText();
                        controller.addDeviceGroup(newGroup);
                        Get.back();
                      },
                      child: const Text('确定'),
                    ),
                  ],
                ),
              );
            },
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: const [
                Icon(Icons.add),
                SizedBox(width: 8),
                Text('新建分组'),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildGroupDropdown() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey),
        borderRadius: BorderRadius.circular(4),
      ),
      child: DropdownButton<String>(
        isExpanded: true,
        underline: const SizedBox(),
        value: controller.deviceGroup.value.isEmpty
            ? controller.deviceGroups.first
            : controller.deviceGroup.value,
        items: controller.deviceGroups
            .map((group) => DropdownMenuItem(
                  value: group,
                  child: Text(group),
                ))
            .toList(),
        onChanged: (value) {
          if (value != null) {
            controller.updateDeviceGroup(value);
          }
        },
      ),
    );
  }

  Widget _buildDeviceConfigStep() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '设备配置',
            style: AppTextStyles.titleLarge,
          ),
          const SizedBox(height: 16),
          Text(
            '设备已准备就绪，点击"完成"按钮完成添加',
            style: AppTextStyles.bodyMedium,
          ),
          const SizedBox(height: 24),
          Card(
            elevation: 2,
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                children: [
                  _buildDeviceInfoItem(
                    '设备名称',
                    controller.deviceName.value,
                    Icons.device_hub,
                  ),
                  const Divider(),
                  _buildDeviceInfoItem(
                    '设备分组',
                    controller.deviceGroup.value,
                    Icons.folder,
                  ),
                  const Divider(),
                  _buildDeviceInfoItem(
                    '设备ID',
                    controller.deviceId.value,
                    Icons.vpn_key,
                  ),
                  const Divider(),
                  _buildDeviceInfoItem(
                    '设备类型',
                    controller.deviceType.value,
                    Icons.category,
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 24),
          CheckboxListTile(
            value: controller.isAdvancedConfig.value,
            onChanged: (value) {
              if (value != null) {
                controller.toggleAdvancedConfig();
              }
            },
            title: const Text('高级配置'),
          ),
          if (controller.isAdvancedConfig.value) _buildAdvancedConfig(),
        ],
      ),
    );
  }

  Widget _buildAdvancedConfig() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 16),
        Text(
          '高级设置',
          style: AppTextStyles.titleMedium,
        ),
        const SizedBox(height: 8),
        Card(
          elevation: 1,
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              children: [
                _buildDeviceInfoItem(
                  '设备IP',
                  controller.deviceIp.value,
                  Icons.wifi,
                ),
                // 其他高级设置项
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildDeviceInfoItem(String label, String value, IconData icon) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        children: [
          Icon(icon, color: AppColors.primary),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  label,
                  style: AppTextStyles.bodySmall.copyWith(color: Colors.grey),
                ),
                Text(
                  value,
                  style: AppTextStyles.bodyMedium,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomBar() {
    return Container(
      padding: const EdgeInsets.all(16.0),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.2),
            spreadRadius: 1,
            blurRadius: 5,
            offset: const Offset(0, -3),
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          if (controller.currentStep.value > 0)
            ElevatedButton(
              onPressed: controller.previousStep,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.white,
                foregroundColor: AppColors.primary,
                side: BorderSide(color: AppColors.primary),
                minimumSize: const Size(120, 50),
              ),
              child: const Text('上一步'),
            )
          else
            const SizedBox(width: 120),
          Text(
            '步骤 ${controller.currentStep.value + 1}/3',
            style: AppTextStyles.bodyMedium,
          ),
          ElevatedButton(
            onPressed: controller.currentStep.value < 2
                ? controller.nextStep
                : controller.addDevice,
            style: ElevatedButton.styleFrom(
              backgroundColor: AppColors.primary,
              minimumSize: const Size(120, 50),
            ),
            child: Text(controller.currentStep.value < 2 ? '下一步' : '完成'),
          ),
        ],
      ),
    );
  }

  Icon _getDeviceIcon(String deviceType) {
    switch (deviceType.toUpperCase()) {
      case 'LIGHT':
        return const Icon(Icons.lightbulb, color: Colors.amber);
      case 'SOCKET':
        return const Icon(Icons.power, color: Colors.green);
      case 'CAMERA':
        return const Icon(Icons.camera_alt, color: Colors.blue);
      case 'SENSOR':
        return const Icon(Icons.sensors, color: Colors.purple);
      default:
        return const Icon(Icons.devices_other, color: Colors.grey);
    }
  }
}